package gis.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.GroundOverlayOptions;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.SpatialRelationUtil;
import com.google.gson.Gson;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import gis.dto.GPS_Record;
import gis.network.http.AreaOperator;
import gis.views.beans.PointXY;
import inter.Download;
import inter.DownloadInfo;
import managers.VolleySingleton;
import utils.ConvertProjection;
import utils.Gps;
import utils.MeasureArea;
import utils.PositionUtil;

import static com.xkh.xkh.R.drawable.location;

public class MapShowActivity extends Activity {
    MapView mMapView = null;
    BaiduMap mBaiduMap = null;
    Button mButtonGetPoint = null;
    Button mButtonDrawPoint = null;
    Button mButtonGetArea;
    Button mButtonClear;
    Button mButtonNear;
    Button mButtonDeleteArea;
    Button mLocation;
    Button back;
    TextView mCurrentAreaButton;

    TextView mArea = null;
    double area = 0;

    boolean isFirstLoaded;

    // 当前标注过的点
    List<LatLng> latLngs = new ArrayList<>();

    // 当前标注过程状态码
    int markStatus = 0;//初始状态为0；第一次点击后，状态为1,之后没点击一次加1；
    // 允许绘制开关
    boolean drawGate = false;
    // 标注过程中加入的标注物
    List<Marker> markers = new ArrayList<>();

    // 地图上的线
    List<OverlayOptions> ooPolylines = new ArrayList<>();

    List<Overlay> lines = new ArrayList<>();

    // 地图上的标注点
    List<Marker> markersAll = new ArrayList<>();

    // 地图上的区域
    List<Area> areas = new ArrayList<>();

    // 当前处理对象
    long currentId = -1;// 默认-1代表添加新面积；若不是-1，则代表要修改的面积id。每次绘制点击的第一个marker所属是当前对象。

    // 地块面积是否绘制完
    boolean AreaSuccess = false;
    // 当前Marker
    Marker currentMarker = null;

    // 当前地块
    Area mCurrentArea = null;

    // 保存地块与地块id的关系
    HashMap<Long,Area> mapIDArea = new HashMap<>();
    private Button mButtonYear;


    // 定位相关
    LatLng latLngLocation = null;
    LocationClient mLocClient;
    BDLocation mBdLocation;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    private static final int accuracyCircleFillColor = 0xAAFFFF88;
    private static final int accuracyCircleStrokeColor = 0xAA00FF00;
//    private SensorManager mSensorManager;
    private Double lastX = 0.0;
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;

    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;
    private float direction;
    private LinearLayout mLinearLayoutHide;
    private Button mButtonMore;
    private Button mButtonHistory;
    private View m_DetailLayout_query;
    private PopupWindow pwDetailInfo_query;
    private TextView m_textfarmDLMC;
    private TextView m_textfarmCode;
    private View m_gpsSave;
    private PopupWindow pwgpsSave;
    private RadioButton handi;
    private RadioButton shvidi;
    private EditText infotext;
    private Button yesButton;
    TextView textview_farmQSDWMC;
    TextView textview_farmZLDWMC;
    private TextView currentIDTv;
    private Overlay boundsOverlaty;
    private GroundOverlayOptions ooGround;

    public static WeakReference<GroundOverlayOptions> weakGroundOverlayOptions;
//    private Sensor sensor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
//        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.map_show3);


        currentIDTv = (TextView) findViewById(R.id.currentID);


        // 弹出地块
        LayoutInflater lfCallOut_query = getLayoutInflater();
        m_DetailLayout_query = lfCallOut_query.inflate(R.layout.farmlandinfo2, null);
        pwDetailInfo_query = new PopupWindow(m_DetailLayout_query, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        m_textfarmDLMC = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmDLMC);
        m_textfarmCode = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmCode);
        textview_farmQSDWMC = (TextView)m_DetailLayout_query.findViewById(R.id.textview_farmQSDWMC);
        textview_farmZLDWMC = (TextView)m_DetailLayout_query.findViewById(R.id.textview_farmZLDWMC);


        // 弹出GPS信息
        m_gpsSave = lfCallOut_query.inflate(R.layout.dialog_savegps, null);
        pwgpsSave = new PopupWindow(m_gpsSave, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        pwgpsSave.setFocusable(true);

        handi = (RadioButton) m_gpsSave.findViewById(R.id.handi);
        shvidi = (RadioButton) m_gpsSave.findViewById(R.id.shuidi);
        infotext = (EditText) m_gpsSave.findViewById(R.id.infoGPSINFO);
        yesButton = (Button)m_gpsSave.findViewById(R.id.commitinfo);

        yesButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                makeNewArea();
                pwgpsSave.dismiss();
            }
        });


        m_DetailLayout_query.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                pwDetailInfo_query.dismiss();

            }
        });




        mLinearLayoutHide = (LinearLayout) findViewById(R.id.linearLayoutHide);
        mButtonMore = (Button) findViewById(R.id.buttonMore);
        mButtonHistory = (Button) findViewById(R.id.buttonHistory);
        mButtonNear = (Button) findViewById(R.id.buttonNear);
        mButtonClear = (Button) findViewById(R.id.buttonClear);
        mButtonMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mLinearLayoutHide.getVisibility()==View.VISIBLE){
                    mLinearLayoutHide.setVisibility(View.GONE);
                }else {
                    int width = mButtonMore.getMeasuredWidth();
                    mButtonHistory.setWidth(width);
                    mButtonNear.setWidth(width);
                    mButtonClear.setWidth(width);
                    mLinearLayoutHide.setVisibility(View.VISIBLE);
                }
            }
        });


//        test2();
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);

        // 开启定位图层
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMyLocationEnabled(true);


        // 开启方向
        // 获得传感器管理器
//        SensorManager mSensorManager = (SensorManager) MyApplication.share()
//                .getSystemService(Context.SENSOR_SERVICE);
//        if (mSensorManager != null)
//        {
//            // 获得方向传感器
//            sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
//        }

        // 启动GPS
        mBdLocation = new BDLocation();
        mLocClient = MyApplication.mLocClient;
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mLocClient.setLocOption(option);
        final MyLocationConfiguration mConfig=new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null);
        mBaiduMap.setMyLocationConfigeration(mConfig);
        mLocClient.start();//开始定位相关
        mBdLocation = mLocClient.getLastKnownLocation();
        if (mBdLocation != null){
            latLngLocation = new LatLng(mBdLocation.getLatitude(),mBdLocation.getLongitude());
        }
       // 添加边界覆盖物
        addOverJPEG();

        // 获取面积显示
        mArea = (TextView) findViewById(R.id.area);

        // 选中区块面积
        mCurrentAreaButton = (TextView)findViewById(R.id.currentArea);

        // 取点
        mButtonGetPoint = (Button) findViewById(R.id.button);
        mButtonGetPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println(mLocClient.isStarted());
                if (!mLocClient.isStarted())
                {
                    mLocClient.start();
                }

                mBdLocation = mLocClient.getLastKnownLocation();


                if (mBdLocation != null){
                    latLngLocation = new LatLng(mBdLocation.getLatitude(),mBdLocation.getLongitude());
                }
                if (latLngLocation != null)
                    setMaker(latLngLocation);
            }
        });
        // 绘图
        mButtonDrawPoint = (Button) findViewById(R.id.button2);
        mButtonDrawPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                drawPoint();

                // 重绘
                redrawLine();

                //
                currentIDTv.setText("");


            }
        });

        // 附近
        mButtonNear = (Button) findViewById(R.id.buttonNear);
        mButtonNear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mBdLocation = mLocClient.getLastKnownLocation();
                if (mBdLocation != null){
                    latLngLocation = new LatLng(mBdLocation.getLatitude(),mBdLocation.getLongitude());
                }


                if (latLngLocation != null)
                {
                    Gps gps = PositionUtil.bd09_To_Gps84(latLngLocation.latitude,latLngLocation.longitude);
                    Double[] result = ConvertProjection.Convert(gps.getWgLon(),gps.getWgLat());

                    int xID = new Double(Math.floor((result[0]-MeasureArea.LEFT)/1000)).intValue();
                    int yID = new Double(Math.floor((MeasureArea.TOP-result[1])/1000)).intValue();
                    int xyID = xID*100000+yID;
                    getNearByArea(xyID);

                }

            }
        });

        // 计算面积
        mButtonGetArea = (Button) findViewById(R.id.buttonSave);
        mButtonGetArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 保存面积记录
                if (currentId == -1)
                {
                    // 新建
                    pwgpsSave.showAtLocation(mMapView,Gravity.CENTER,0,0);


                }
                else
                {
                    // 修改
                    changeArea(currentId);
                }
            }
        });

        //  清楚标记物
        mButtonClear = (Button) findViewById(R.id.buttonClear);
        mButtonClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBaiduMap.clear();
                addOverJPEG();
                for (Area a:areas)
                {
                    a.getmOverlay().remove();
                }
                areas.clear();
                markers.clear();
                markersAll.clear();
                ooPolylines.clear();
                markStatus = 0;
            }
        });

        // 按年获取地块
        mButtonYear = (Button) findViewById(R.id.buttonHistory);
        mButtonYear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                DatePickerDialog mDialog;
                // 解决三星弹出框问题
                if(Integer.valueOf(Build.VERSION.SDK) >= Build.VERSION_CODES.LOLLIPOP)
                {
                    mDialog = new DatePickerDialog(MapShowActivity.this,R.style.SpecialDatePicker, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                            System.out.println(""+i);
                            getAreaByYear(i);
                        }

                    }, Calendar.getInstance().get(Calendar.YEAR),1,1);
                }
                else
                {
                    mDialog = new DatePickerDialog(MapShowActivity.this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                            System.out.println(""+i);
                            getAreaByYear(i);
                        }

                    }, Calendar.getInstance().get(Calendar.YEAR),1,1);
                }




                mDialog.show();
                DatePicker dp = mDialog.getDatePicker();
                ((ViewGroup) (((ViewGroup) dp.getChildAt(0)).getChildAt(0)))
                        .getChildAt(1).setVisibility(View.GONE);
                ((ViewGroup) (((ViewGroup) dp.getChildAt(0)).getChildAt(0)))
                        .getChildAt(2).setVisibility(View.GONE);

            }
        });

        // 定位到当前位置
        mLocation = (Button) findViewById(R.id.location_myloc);
        mLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BDLocation location = mLocClient.getLastKnownLocation();
                if (location == null)return;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
//                ll = new LatLng(45.0252,132.9684);
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                // 保存位置到服务器
                saveMyLocation(ll);
            }
        });

        // 返回
        back = (Button) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MapShowActivity.this.finish();
            }
        });

        // 删除当前标记的面积
        mButtonDeleteArea = (Button) findViewById(R.id.buttonDelete);
        mButtonDeleteArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentId != -1) {
                    new AlertDialog.Builder(MapShowActivity.this).setTitle("是否删除？")
                            .setMessage("是否确认删除地块，id为"+currentId)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    deleteTheArea(currentId);
                                }
                            }).show();
                }
                else
                {
                    Toast.makeText(MyApplication.share(),"没有选中当前地块",Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 地图上标注物点击事件
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {
                // 如果点击的是地块对应的标记，弹出面积显示
                if (marker.getExtraInfo().get("type") != null && marker.getExtraInfo().getLong("type")==2)
                {
                    if (marker.getExtraInfo().get("areaID") != null)
                    {
                        Area a = mapIDArea.get(marker.getExtraInfo().get("areaID"));
                        showAreaInfo(a);
                    }
                    return false;
                }


                // 若已经成功，则必须重绘
                if (AreaSuccess)
                {
                    Toast.makeText(MyApplication.share(),"请点击重绘", Toast.LENGTH_SHORT).show();
                    return false;
                }


                if (!drawGate)
                {
                    return false;
                }
                markStatus ++;

                // 如果是绘制的第一个点，则标识出所属id
                if (markStatus == 1)
                {
                    Long id = marker.getExtraInfo().getLong("areaID");
                    currentId = id;
                    mCurrentArea = mapIDArea.get(currentId);
                    BitmapDescriptor bitmap = BitmapDescriptorFactory
                            .fromResource(R.drawable.green);
                    marker.setIcon(bitmap);
                    currentMarker = marker;
                    currentIDTv.setText("当前操作地块 id="+(id==-1?"(新地块)":id));
                    System.out.println("第一次绘制id："+id);
                }

                // 如果没有添加过，则添加
                if (!markers.contains(marker))
                {
                    markers.add(marker);
                    // 标注物语标注物之间添加线
                    if (markStatus != 1)
                    {
                        addLine(markers.get(markers.size()-2),markers.get(markers.size()-1));
                    }
                }
                // 如果形成环形
                if (markers.size()>2&&markers.get(0) == marker)
                {
                    markers.add(marker);
                    // 标注物语标注物之间添加线
                    if (markStatus != 1)
                    {
                        addLine(markers.get(markers.size()-2),markers.get(markers.size()-1));
                    }

                    // 计算面积
                    double area = getArea();
                    MapShowActivity.this.area = Math.ceil(area);
                    AreaSuccess = true;
                    mArea.setText(MapShowActivity.this.area+"平方米");
                }

                return false;
            }
        });

        // 地图区块长按事件
        mBaiduMap.setOnMapLongClickListener(new BaiduMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {
                System.out.println(latLng.latitude+","+latLng.longitude);
                SpatialRelationUtil spatialRelationUtil = new SpatialRelationUtil();
                for (Area a:areas)
                {
                    boolean isInFlag = spatialRelationUtil.isPolygonContainsPoint(a.points,latLng);
                    if (isInFlag)
                    {
                        // 在区块长按，显示区块边界，并修改
                        makeAreaEditable(a);

                    }
                }
            }
        });



        // 地图区块长按事件
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng latLng) {
                SpatialRelationUtil spatialRelationUtil = new SpatialRelationUtil();
                for (Area a:areas)
                {
                    boolean isInFlag = spatialRelationUtil.isPolygonContainsPoint(a.points,latLng);
                    if (isInFlag)
                    {
                        // 在区块长按，显示区块边界，并修改
                        showAreaInfo(a);

                    }
                }
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });


        mBaiduMap.setBuildingsEnabled(false);
        // 监听地图的缩放级别
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                System.out.println(mapStatus.zoom);
                if (boundsOverlaty == null)
                {
                    addOverJPEG();
                    return;
                }
                if (mapStatus.zoom<12.5f)
                {
                    boundsOverlaty.setVisible(true);
                }
                else
                {
                    boundsOverlaty.setVisible(false);
                }
            }
        });

    }

    // 保存我的最新位置
    private void saveMyLocation(final LatLng ll) {

        mLocation.setEnabled(false);

        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/SaveMyGPSLocation";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.startsWith("{"))
                        {
                            Download download = new Gson().fromJson(response,Download.class);
                            if (download.getStatus() == DownloadInfo.SUCCESS)
                            {
                                //
                            }
                            else
                            {
                                //
                            }
                            mLocation.setEnabled(true);
                        }
                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mLocation.setEnabled(true);
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("account",MyApplication.getOwnUser().getUser_RealName());
                map.put("location",ll.latitude+","+ll.longitude);
                map.put("time", Calendar.getInstance().getTimeInMillis()+"");

                return map;
            }

            @Override
            protected com.android.volley.Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return com.android.volley.Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }


    // 显示面积信息
    private void showAreaInfo(Area a) {
     // 显示a的面积
        m_textfarmCode.setText(a.getId()+"");
        m_textfarmDLMC.setText(a.getType());
        textview_farmQSDWMC.setText(a.getArea()+"平方米");
        textview_farmZLDWMC.setText(a.getInfo());

        pwDetailInfo_query.showAtLocation(mMapView, Gravity.NO_GRAVITY, 8, 50); // popwindow的显示位置
    }

    // 重绘画线
    private void redrawLine() {



        // 第一次点击绘制
        if (!drawGate)
        {
            drawGate = true;
            return;
        }

        // 不是第一次点击绘制，就是重绘
        for (Overlay o:lines)
        {
            o.remove();
        }
        if (currentMarker != null)
        {
            currentMarker.setIcon(BitmapDescriptorFactory
                    .fromResource(R.drawable.red_maker));
        }
        lines.clear();
        ooPolylines.clear();
        markStatus = 0;
        AreaSuccess = false;
        markers.clear();
        mArea.setText("");
        currentId = -1;
    }

    // 删除当前面积
    private void deleteTheArea(final long currentId) {

        new AreaOperator().deleteArea(currentId,new AreaOperator.Response(){
            @Override
            public void onResult(boolean success, Object result) {

                if (success)
                {
                    Toast.makeText(MyApplication.share(),"删除成功",Toast.LENGTH_LONG).show();
                    MapShowActivity.this.currentId  = -1;
                    currentIDTv.setText("");
                    eraseTheArea(currentId);
                }
                else {
                    Toast.makeText(MyApplication.share(),"删除失败",Toast.LENGTH_LONG).show();
                }

            }
        });
    }

    // 从地图上删除区块面积
    private void eraseTheArea(long areaID) {
        Area a = mapIDArea.get(areaID);
        for (Marker m:a.getEdegMarkers())
        {
            m.remove();
        }

        a.getmOverlay().remove();

        if (a.getMiddle() != null)
        {
            a.getMiddle().remove();
        }

        areas.remove(a);
        mapIDArea.remove(areaID);
    }


    // 获取附近的点
    private void getAreaByYear(int year) {
        mButtonYear.setEnabled(false);
        new AreaOperator().getAreaByYear(year,new AreaOperator.Response(){
            @Override
            public void onResult(boolean success, Object result) {

                if (success)
                {
                    Toast.makeText(MyApplication.share(),"获取成功",Toast.LENGTH_SHORT).show();
                    AreaOperator.NearByDownload download = (AreaOperator.NearByDownload) result;
                    // 更新Area
                    // 清理Area
                    for (Area area:areas)
                    {
                        area.getmOverlay().remove();
                        if (area.getMiddle() != null)
                        {
                            area.getMiddle().remove();
                        }
                    }
                    areas.clear();


                    // 绘制Area
                    for (GPS_Record gps_record:download.getRecords())
                    {
                        Area a = new Area();
                        // 获取记录点
                        String record = gps_record.getRecord();
                        String[] records = record.split(";");
                        double sumx = 0;
                        double sumy = 0;
                        for (String r:records)
                        {
                            if (!r.equals(""))
                            {
                                // 获取经度和纬度
                                String[] latlon = r.split(",");
                                sumx += Double.parseDouble(latlon[0]);
                                sumy += Double.parseDouble(latlon[1]);
                                a.getPoints().add(new LatLng(Double.parseDouble(latlon[0]),Double.parseDouble(latlon[1])));
                            }
                        }
                        if (a.getPoints().size() != 0)
                            a.setMiddlePoint(new LatLng(sumx/a.getPoints().size(),sumy/a.getPoints().size()));
                        // 获取地块编号
                        a.setId(gps_record.getId());

                        // 获取面积
                        a.setArea(Double.parseDouble(gps_record.getArea()));
                        // 其他待处理
                        a.setInfo(gps_record.getRemark());
                        a.setType(gps_record.getType());

                        // 添加到绘制地块中
                        areas.add(a);

                    }
                    // 绘制出来地块
                    drawArea(areas);


                    //定位到兴凯湖
                    LatLng ll = new LatLng(45.263869,132.7990188);
//                ll = new LatLng(45.0252,132.9684);
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(ll).zoom(11.0f);

                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                }
                else {
                    Toast.makeText(MyApplication.share(),"获取失败",Toast.LENGTH_LONG).show();
                }
                mButtonYear.setEnabled(true);
            }
        });
    }


    // 获取附近的点
    private void getNearByArea(int indexID) {
        mButtonNear.setEnabled(false);
        new AreaOperator().getNearByArea(indexID,new AreaOperator.Response(){
            @Override
            public void onResult(boolean success, Object result) {

                if (success)
                {
                    Toast.makeText(MyApplication.share(),"获取成功",Toast.LENGTH_SHORT).show();
                    AreaOperator.NearByDownload download = (AreaOperator.NearByDownload) result;
                    // 更新Area
                    // 清理Area
                    for (Area area:areas)
                    {
                        area.getmOverlay().remove();
                        if (area.getMiddle() != null)
                        {
                            area.getMiddle().remove();
                        }
                    }
                    areas.clear();


                    // 绘制Area
                    for (GPS_Record gps_record:download.getRecords())
                    {
                        Area a = new Area();
                        // 获取记录点
                        String record = gps_record.getRecord();
                        String[] records = record.split(";");
                        double sumx = 0;
                        double sumy = 0;
                        for (String r:records)
                        {
                            if (!r.equals(""))
                            {

                                // 获取经度和纬度
                                String[] latlon = r.split(",");
                                sumx += Double.parseDouble(latlon[0]);
                                sumy += Double.parseDouble(latlon[1]);
                                a.getPoints().add(new LatLng(Double.parseDouble(latlon[0]),Double.parseDouble(latlon[1])));
                            }
                        }

                        if (a.getPoints().size() != 0)
                            a.setMiddlePoint(new LatLng(sumx/a.getPoints().size(),sumy/a.getPoints().size()));
                        // 获取地块编号
                        a.setId(gps_record.getId());
                        // 获取面积
                        a.setArea(Double.parseDouble(gps_record.getArea()));
                        // 其他待处理
                        a.setInfo(gps_record.getRemark());
                        a.setType(gps_record.getType());

                        // 添加到绘制地块中
                        areas.add(a);
                    }
                    // 绘制出来地块
                    drawArea(areas);



                    BDLocation location = mLocClient.getLastKnownLocation();
                    if (location == null)return;
                    LatLng ll = new LatLng(location.getLatitude(),
                            location.getLongitude());
//                ll = new LatLng(45.0252,132.9684);
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(ll);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                }
                else {
                    Toast.makeText(MyApplication.share(),"获取失败",Toast.LENGTH_LONG).show();
                }
                mButtonNear.setEnabled(true);
            }
        });
    }

    // 修改已有的面积地块测量
    private void changeArea(final long currentId) {

        // 判断绘制的点数
        if (markers.size() < 3)
        {
            Toast.makeText(MyApplication.share(),"绘制坐标数目不得少于3",Toast.LENGTH_SHORT).show();
            return;
        }

        // 讲标注的点加入到地块中去
        final Area area = new Area();
        for (Marker m:markers)
        {
            area.getPoints().add(m.getPosition());
        }
        area.setArea(Math.ceil(MapShowActivity.this.area));
        area.setId(currentId);
        mButtonGetArea.setEnabled(false);
        new AreaOperator().changeArea(area,new AreaOperator.Response(){
            @Override
            public void onResult(boolean success, Object result) {

                if (success)
                {
                    Toast.makeText(MyApplication.share(),"修改成功",Toast.LENGTH_LONG).show();
                    changeAreaOnLocalMap(currentId,area);
                    currentIDTv.setText("");
                    MapShowActivity.this.currentId = -1;
                }
                else {
                    Toast.makeText(MyApplication.share(),"修改失败",Toast.LENGTH_LONG).show();
                }
                mButtonGetArea.setEnabled(true);
            }
        });
    }

    // 在地图上修改当前面积
    private void changeAreaOnLocalMap(long currentId, Area area) {
        Area before = mapIDArea.get(currentId);
        area.setType(before.getType());
        area.setInfo(before.getInfo());
        eraseTheArea(currentId);
        area.getPoints().remove(area.getPoints().size()-1);
        List<Area> areas = new ArrayList<>();
        areas.add(area);
        drawArea(areas);
        MapShowActivity.this.areas.add(area);
        // 清楚多余的markers
        deleteMarkers();
        redrawLine();


    }

    // 删除markers
    private void deleteMarkers() {
        for(Marker m:markers)
        {
            m.remove();
        }
    }

    // 删除markers
    private void deleteMarkersOver() {
        for(Marker m:markers)
        {
            if (m.getExtraInfo().getLong("areaID") == -1)
            {
                m.remove();
            }
        }
    }

    // 新建新的地块测量
    private void makeNewArea() {

        // 判断绘制的点数
        if (markers.size() < 3)
        {
            Toast.makeText(MyApplication.share(),"绘制坐标数目不得少于3",Toast.LENGTH_SHORT).show();
            return;
        }

        if (currentId == -1&& AreaSuccess)
        {
            // 讲标注的点加入到地块中去
            final Area area = new Area();
            for (Marker m:markers)
            {
                area.getPoints().add(m.getPosition());
            }
            area.setArea(Math.ceil(MapShowActivity.this.area));
            if (handi.isChecked())
            {
                area.setType("旱地");
            }
            else
            {
                area.setType("水地");
            }
            area.setInfo(infotext.getText().toString());
            mButtonGetArea.setEnabled(false);
            new AreaOperator().addNewArea(area,new AreaOperator.Response(){
                @Override
                public void onResult(boolean success, Object result) {

                    if (success)
                    {
                        AreaOperator.Download2 download2 = (AreaOperator.Download2) result;
                        Toast.makeText(MyApplication.share(),"保存成功",Toast.LENGTH_LONG).show();
                        area.setId(download2.getId());
                        addNewAreaLocalMap(area);
                    }
                    else {
                        Toast.makeText(MyApplication.share(),"保存失败",Toast.LENGTH_LONG).show();
                    }
                    mButtonGetArea.setEnabled(true);
                }
            });
        }
    }

    // 添加新的面积
    private void addNewAreaLocalMap(Area area) {
        area.getPoints().remove(area.getPoints().size()-1);
        List<Area> areas = new ArrayList<>();
        areas.add(area);
        drawArea(areas);
        MapShowActivity.this.areas.add(area);
        // 清楚多余的markers
        deleteMarkersOver();

        redrawLine();
    }

    // 在区块周围添加marker使其可以编辑
    private void makeAreaEditable(Area a) {
        if (a.mEditable)
        {
            a.mEditable = false;
            // 使其不可修改
            for (Marker m:a.edegMarkers)
            {
                m.remove();

            }

        }
        else
        {
            a.mEditable = true;
            // 使其可以修改
            for (LatLng latLng:a.points)
            {
                Marker m = (Marker) setMaker(latLng,a.id);
                a.edegMarkers.add(m);
            }
        }

       /* // 显示a的面积
        if (a.ismEditable())
        {
            mCurrentAreaButton.setText("选中区块面积:"+a.area+"平方米");
        }
        else
        {
            mCurrentAreaButton.setText("");
        }*/

    }

    // 计算面积
    public double getArea(){
        List<PointXY> pointXies = new ArrayList<>();
        for (Marker marker:markers)
        {

            Gps gps = PositionUtil.bd09_To_Gps84(marker.getPosition().latitude,marker.getPosition().longitude);
            Double[] xys = ConvertProjection.Convert(gps.getWgLon(),gps.getWgLat());
            pointXies.add(new PointXY(xys[0],xys[1]));
        }
        PointXY[] pointXies1 = new PointXY[pointXies.size()];
        for (int i=0;i<pointXies.size();i++)
        {
            pointXies1[i] = pointXies.get(i);
        }
        return MeasureArea.area(pointXies1);
    }

    private void addOverJPEG() {
        //定义Ground的显示地理范围
        LatLng southwest = new LatLng(45+59.0/60+14.0/3600, 132+3.0/60+59.0/3600);
        LatLng northeast = new LatLng(45+1.0/60+1.0/3600, 133+39.0/60+47.0/3600);

//        LatLng southwest = new LatLng(132+3.0/60+59.0/3600,45+59.0/60+14.0/3600);
//        LatLng northeast = new LatLng(133+39.0/60+47.0/3600,45+1.0/60+1.0/3600);

        southwest = convertTOBD09(southwest);
        northeast = convertTOBD09(northeast);

        LatLng southwest2 = new LatLng(southwest.latitude+0.02,southwest.longitude-0.02);
        LatLng northeast2 = new LatLng(northeast.latitude-0.01,northeast.longitude+0.02);
        LatLngBounds bounds = new LatLngBounds.Builder()
                .include(southwest2)
                .include(northeast2)
                .build();

        if (!isFirstLoaded)
        {
            isFirstLoaded = true;
            if (weakGroundOverlayOptions != null)
            {
                ooGround = weakGroundOverlayOptions.get();
                boundsOverlaty = mBaiduMap.addOverlay(ooGround);
                return;
            }

        }

        if (ooGround == null)
        {
            //定义Ground显示的图片
            BitmapDescriptor bdGround = BitmapDescriptorFactory
                    .fromResource(R.drawable.kaige);
            //定义Ground覆盖物选项
             ooGround = new GroundOverlayOptions()
                    .positionFromBounds(bounds)
                    .image(bdGround)
                    .transparency(0.8f);

        }

        //在地图中添加Ground覆盖物
        boundsOverlaty = mBaiduMap.addOverlay(ooGround);
    }

    // 标注物之间画线
    private void addLine( Marker before, Marker next) {
        List<LatLng> points = new ArrayList<>();
        points.add(before.getPosition());
        points.add(next.getPosition());
        OverlayOptions ooPolyline = new PolylineOptions().width(10).color(Color.BLUE).points(points);
        ooPolylines.add(ooPolyline);
        Overlay overlay = mBaiduMap.addOverlay(ooPolyline);
        lines.add(overlay);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        // 退出时销毁定位
        mLocClient.unRegisterLocationListener(myListener);
        mLocClient.stop();

        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        mLocClient.start();


//        SensorManager mSensorManager = (SensorManager) MyApplication.share()
//                .getSystemService(Context.SENSOR_SERVICE);
//        //为系统的方向传感器注册监听器
//        if (sensor!=null)
//        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
//                SensorManager.SENSOR_DELAY_UI);

    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();

        mLocClient.stop();
        //取消注册传感器监听
//        if (sensor!=null)
//            mSensorManager.unregisterListener(this);

    }

    //在地图中添加Ground覆盖物
    private Overlay setMaker(LatLng point){
        Overlay overlay = setMaker(point,-1);
        return overlay;
    }


    //在地图中添加Ground覆盖物
    private Overlay setMaker(LatLng point,long currentId){
        //定义Maker坐标点
//        LatLng point = new LatLng(39.963175, 116.400244);
    //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.red_maker);
    //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);

    //在地图上添加Marker，并显示
        Overlay overlay = mBaiduMap.addOverlay(option);


        Marker m = (Marker) overlay;

        Bundle bundle = new Bundle();
        bundle.putLong("areaID",currentId);
        m.setExtraInfo(bundle);
//        MapStatus.Builder builder = new MapStatus.Builder();
//        builder.target(point);
//        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        return overlay;
    }


    //在地图中添加测过面积标注
    private Overlay setMaker2(LatLng point,long currentId,Long type){
        //定义Maker坐标点
//        LatLng point = new LatLng(39.963175, 116.400244);
        //构建Marker图标

        View view=getLayoutInflater().inflate(R.layout.areaid,null);
        TextView icon = (TextView) view.findViewById(R.id.area_icon);
        icon.setTypeface(MyApplication.iconfont);
        TextView textView = (TextView) view.findViewById(R.id.area_name);
        textView.setText(currentId+"");

        Bitmap bm = getViewBitmap(view);
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromBitmap(bm);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);

        //在地图上添加Marker，并显示
        Overlay overlay = mBaiduMap.addOverlay(option);


        Marker m = (Marker) overlay;

        Bundle bundle = new Bundle();
        bundle.putLong("areaID",currentId);
        bundle.putLong("type",type);
        m.setExtraInfo(bundle);

        return overlay;
    }

    // 绘制区域
    private void drawArea(List<Area> areas){
        for (Area a:areas)
        {
            mapIDArea.put(a.id,a);
            //构建用户绘制多边形的Option对象
            OverlayOptions polygonOption = new PolygonOptions()
                    .points(a.points)
                    .stroke(new Stroke(5, 0xAA00FF00))
                    .fillColor(0xAAFFFF00);
            //在地图上添加多边形Option，用于显示
            Overlay areaOverlay = mBaiduMap.addOverlay(polygonOption);
            a.mOverlay = areaOverlay;

            // 在地图上加入标注
            if (a.middlePoint != null)
            {
                Overlay markershow = setMaker2(a.middlePoint,a.getId(),2l);
                a.midlleOverlay = markershow;
                a.setMiddle((Marker) markershow);
            }



        }

    }
    //gps坐标转换成百度坐标
    private LatLng convertTOBD09(LatLng sourceLatLng){
        // 将GPS设备采集的原始GPS坐标转换成百度坐标
        CoordinateConverter converter  = new CoordinateConverter();
        converter.from(com.baidu.mapapi.utils.CoordinateConverter.CoordType.GPS);
        // sourceLatLng待转换坐标
        converter.coord(sourceLatLng);
        LatLng desLatLng = converter.convert();
        return desLatLng;
    }

//    @Override
//    public void onSensorChanged(SensorEvent sensorEvent) {
//        double x = sensorEvent.values[SensorManager.DATA_X];
//        if (Math.abs(x - lastX) > 1.0) {
//            mCurrentDirection = (int) x;
//            locData = new MyLocationData.Builder()
//                    .accuracy(mCurrentAccracy)
//                    // 此处设置开发者获取到的方向信息，顺时针0-360
//                    .direction(mCurrentDirection).latitude(mCurrentLat)
//                    .longitude(mCurrentLon).build();
//            mBaiduMap.setMyLocationData(locData);
//
//        }
//        lastX = x;
//
//    }

//    @Override
//    public void onAccuracyChanged(Sensor sensor, int i) {
//
//    }

    public static class  Area
    {


        List<LatLng> points = new ArrayList<>();
        long id;
        Overlay mOverlay = null;
        boolean mEditable = false;
        List<Marker> edegMarkers = new ArrayList<>();
        double area;
        LatLng middlePoint;
        String info;
        String type;
        Overlay midlleOverlay = null;
        Marker middle = null;
        public String getInfo() {
            return info;
        }

        public void setInfo(String info) {
            this.info = info;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public List<LatLng> getPoints() {
            return points;
        }

        public void setPoints(List<LatLng> points) {
            this.points = points;
        }

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public Overlay getmOverlay() {
            return mOverlay;
        }

        public void setmOverlay(Overlay mOverlay) {
            this.mOverlay = mOverlay;
        }

        public boolean ismEditable() {
            return mEditable;
        }

        public void setmEditable(boolean mEditable) {
            this.mEditable = mEditable;
        }

        public List<Marker> getEdegMarkers() {
            return edegMarkers;
        }

        public void setEdegMarkers(List<Marker> edegMarkers) {
            this.edegMarkers = edegMarkers;
        }

        public double getArea() {
            return area;
        }

        public void setArea(double area) {
            this.area = area;
        }

        public LatLng getMiddlePoint() {
            return middlePoint;
        }

        public void setMiddlePoint(LatLng middlePoint) {
            this.middlePoint = middlePoint;
        }

        public Marker getMiddle() {
            return middle;
        }

        public void setMiddle(Marker middle) {
            this.middle = middle;
        }

        public Area() {
        }

        public Area(List<LatLng> points, long id, Overlay mOverlay) {
            this.points = points;
            this.id = id;
            this.mOverlay = mOverlay;
        }
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
//            Toast.makeText(MapShowActivity.this,"定位成功",Toast.LENGTH_SHORT).show();
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
//                ll = new LatLng(45.0252,132.9684);
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));


            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }




    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);
        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());
        addViewContent.buildDrawingCache();

        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }
}
